package oakclub.model;

import oakclub.jooq.Tables;
import oakclub.jooq.tables.ChatRosters;
import oakclub.jooq.tables.Likes;
import oakclub.jooq.tables.NotchatMutualmatch;
import oakclub.jooq.tables.NotviewedMutualmatch;
import org.jooq.DSLContext;
import org.jooq.Field;
import org.jooq.impl.DSL;

import java.sql.Timestamp;

public class MutualMatchModel extends BaseModel
{
    public void view(long userId, long targetId) throws Exception
    {
        this.execute(new IExecute()
        {
            @Override
            public void execute(DSLContext context, Object... params) throws Exception
            {
                // params
                long userId = (long) params[0];
                long targetId = (long) params[1];

                // table alias
                NotviewedMutualmatch NVMM = Tables.NOTVIEWED_MUTUALMATCH;
                NotchatMutualmatch NCMM = Tables.NOTCHAT_MUTUALMATCH;

                // remove notviewed_mutualmatch
                context
                    .delete(NVMM)
                    .where(NVMM.USER_ID.eq(userId), NVMM.TARGET_ID.eq(targetId))
                    .execute();

                // remove notchat_mutualmatch
                context
                    .delete(NCMM)
                    .where(NCMM.USER_ID.eq(userId), NCMM.TARGET_ID.eq(targetId))
                    .execute();
            }
        }, userId, targetId);
    }

    public void syncWithChatList() throws Exception
    {
        this.execute(new IExecute()
        {
            @Override
            public void execute(DSLContext context, Object... params) throws Exception
            {
                // table alias
                ChatRosters CR = Tables.CHAT_ROSTERS;
                Likes L1 = Tables.LIKES.as("l1");
                Likes L2 = Tables.LIKES.as("l2");

                // sync
                Field<Timestamp> createdTime = DSL.currentTimestamp();
                Field<Short> unreadNum = DSL.val((short) 0);
                Field<String> lastMessage = DSL.val("");
                Field<Timestamp> lastMessageTime = null;
                Field<Timestamp> lastActiveTime = DSL.currentTimestamp();
                context
                    .insertInto(CR, CR.USER_ID, CR.TARGET_ID, CR.CREATED_TIME, CR.UNREAD_NUM, CR.LAST_MESSAGE, CR.LAST_MESSAGE_TIME, CR.LAST_ACTIVE_TIME)
                    .select(context
                        .select(L1.USER_ID, L1.TARGET_ID, createdTime, unreadNum, lastMessage, lastMessageTime, lastActiveTime)
                        .from(L1)
                        .join(L2).on(L1.USER_ID.eq(L2.TARGET_ID), L1.TARGET_ID.eq(L2.USER_ID), L2.IS_LIKE.eq((short) 1))
                        .leftOuterJoin(CR).on(L1.USER_ID.eq(CR.USER_ID), L2.TARGET_ID.eq(CR.TARGET_ID))
                        .where(L1.IS_LIKE.eq((short) 1), CR.USER_ID.isNull()))
                    .execute();
            }
        });
    }
}
